"use client";

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { notFound } from 'next/navigation';
import { login } from '../../api/api';
import DOMPurify from 'dompurify';
import axios from 'axios';
import { API_BASE_URL } from "@/app/config/config";

export default function ArticleDetailPage({ params }) {
    const { id } = params;
    const [article, setArticle] = useState(null);

    useEffect(() => {
        const fetchArticle = async () => {
            if (id) {
                try {
                    const token = await login();
                    const response = await axios.get(`${API_BASE_URL}/blog/blog/${id}`, {
                        headers: {
                            'Authorization': token
                        }
                    });
                    if (response.data.code === 200) {
                        setArticle(response.data.data);
                    } else {
                        notFound();
                    }
                } catch (error) {
                    console.error('Error fetching article:', error);
                    notFound();
                }
            }
        };

        fetchArticle();
    }, [id]);

    if (!article) {
        return <p>Loading...</p>;
    }

    return (
        <div className="flex flex-col md:flex-row justify-center">
            <main className="p-4">
                <h1 className="text-3xl font-bold mb-4 text-center">{article.title}</h1>
                <div
                    className="prose"
                    dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(article.content) }}
                />
            </main>
        </div>
    );
}
